package com.eduagent.xwqeduagent.controller;

import com.eduagent.xwqeduagent.api.RecordingFileTranscription.model.ResultQueryResponse;
import com.eduagent.xwqeduagent.api.RecordingFileTranscription.model.UploadResponse;
import com.eduagent.xwqeduagent.api.RecordingFileTranscription.service.FileTranscriptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件转写控制器
 */
@RestController
@RequestMapping("/file-transcription")
@Slf4j
public class FileTranscriptionController {

    @Autowired
    private FileTranscriptionService fileTranscriptionService;
    
    /**
     * 上传录音文件进行转写（支持高级参数）
     * 
     * @param file 录音文件
     * @param duration 录音时长（毫秒）
     * @param language 语种
     * @param pd 领域
     * @param hotWord 热词，用以提升专业词汇的识别率，格式：热词1|热词2|热词3
     * @param candidate 多候选开关，0：关闭(默认)，1：打开
     * @param roleType 是否开启角色分离，0：不开启(默认)，1：通用角色分离
     * @param roleNum 说话人数，取值范围0-10，默认为0进行盲分
     * @param languageType 语言识别模式选择，1：自动中英文模式(默认)，2:中文模式，4:纯中文模式
     * @return 上传结果
     */
    @PostMapping("/upload/advanced")
    public ResponseEntity<Map<String, Object>> uploadFileAdvanced(
            @RequestParam("file") MultipartFile file,
            @RequestParam("duration") Long duration,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam(value = "pd", required = false) String pd,
            @RequestParam(value = "hotWord", required = false) String hotWord,
            @RequestParam(value = "candidate", required = false) Short candidate,
            @RequestParam(value = "roleType", required = false) Short roleType,
            @RequestParam(value = "roleNum", required = false) Short roleNum,
            @RequestParam(value = "languageType", required = false) Integer languageType) {
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("录音文件不能为空"));
            }
            
            // 检查文件大小（限制为500MB）
            if (file.getSize() > 500 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse("录音文件大小超过500MB限制"));
            }
            
            // 上传文件
            UploadResponse response = fileTranscriptionService.uploadFile(
                file, duration, language, pd, hotWord, candidate, roleType, roleNum, languageType);
            
            // 检查上传结果
            if (!response.isSuccess()) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        "上传失败: " + response.getCode() + " - " + response.getDescInfo()));
            }
            
            // 返回上传结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("orderId", response.getContent().getOrderId());
            result.put("taskEstimateTime", response.getContent().getTaskEstimateTime());

            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("上传录音文件失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("上传录音文件失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传录音文件URL进行转写（支持高级参数）
     * 
     * @param audioUrl 录音文件URL
     * @param fileName 文件名
     * @param duration 录音时长（毫秒）
     * @param language 语种
     * @param pd 领域
     * @param hotWord 热词，用以提升专业词汇的识别率，格式：热词1|热词2|热词3
     * @param candidate 多候选开关，0：关闭(默认)，1：打开
     * @param roleType 是否开启角色分离，0：不开启(默认)，1：通用角色分离
     * @param roleNum 说话人数，取值范围0-10，默认为0进行盲分
     * @param languageType 语言识别模式选择，1：自动中英文模式(默认)，2:中文模式，4:纯中文模式
     * @return 上传结果
     */
    @PostMapping("/upload-url/advanced")
    public ResponseEntity<Map<String, Object>> uploadFileUrlAdvanced(
            @RequestParam("audioUrl") String audioUrl,
            @RequestParam("fileName") String fileName,
            @RequestParam("duration") Long duration,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam(value = "pd", required = false) String pd,
            @RequestParam(value = "hotWord", required = false) String hotWord,
            @RequestParam(value = "candidate", required = false) Short candidate,
            @RequestParam(value = "roleType", required = false) Short roleType,
            @RequestParam(value = "roleNum", required = false) Short roleNum,
            @RequestParam(value = "languageType", required = false) Integer languageType) {
        
        try {
            // 上传文件URL
            UploadResponse response = fileTranscriptionService.uploadFileUrl(
                audioUrl, fileName, duration, language, pd, hotWord, candidate, roleType, roleNum, languageType);
            
            // 检查上传结果
            if (!response.isSuccess()) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        "上传失败: " + response.getCode() + " - " + response.getDescInfo()));
            }
            
            // 返回上传结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("orderId", response.getContent().getOrderId());
            result.put("taskEstimateTime", response.getContent().getTaskEstimateTime());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("上传录音文件URL失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("上传录音文件URL失败: " + e.getMessage()));
        }
    }
    
    /**
     * 轮询查询转写结果 - 自动重试直到完成或达到最大次数
     * 
     * @param orderId 订单ID
     * @param maxRetries 最大重试次数，默认为10次
     * @param intervalSeconds 轮询间隔（秒），默认为5秒
     * @return 查询结果
     */
    @GetMapping("/result/polling/{orderId}")
    public ResponseEntity<Map<String, Object>> getResultWithPolling(
            @PathVariable("orderId") String orderId,
            @RequestParam(value = "maxRetries", defaultValue = "10") int maxRetries,
            @RequestParam(value = "intervalSeconds", defaultValue = "5") int intervalSeconds) {
        try {
            log.info("开始轮询查询转写结果，订单ID: {}，最大重试次数: {}，轮询间隔: {}秒", 
                    orderId, maxRetries, intervalSeconds);
            
            // 查询结果（带轮询）
            ResultQueryResponse response = fileTranscriptionService.queryResultWithPolling(
                    orderId, maxRetries, intervalSeconds);
            
            // 检查查询结果
            if (!response.isSuccess()) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                        "查询失败: " + response.getCode() + " - " + response.getDescInfo()));
            }
            
            // 返回查询结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", response.getContent());
            
            // 获取订单状态
            Integer status = null;
            if (response.getContent() != null && response.getContent().getOrderInfo() != null) {
                status = response.getContent().getOrderInfo().getStatus();
            }
            
            result.put("status", status);
            result.put("statusDescription", getStatusDescription(status));
            
            // 如果未完成，添加提示信息
            if (status != null && status != 4 && status != -1) {
                result.put("message", "轮询已达到最大重试次数，但任务仍未完成，请稍后再次查询");
            }
            log.info("查询结果: {}", result);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("轮询查询转写结果失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("轮询查询转写结果失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建错误响应
     * 
     * @param message 错误信息
     * @return 错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("error", message);
        return response;
    }
    
    /**
     * 获取状态描述
     * 
     * @param status 状态码
     * @return 状态描述
     */
    private String getStatusDescription(Integer status) {
        if (status == null) {
            return "未知状态";
        }
        
        switch (status) {
            case 0:
                return "排队中";
            case 3:
                return "转写中";
            case 4:
                return "转写完成";
            case -1:
                return "转写失败";
            default:
                return "未知状态";
        }
    }
} 